<template>
  <div class="radio-group">
    <div class="radio" :class="option.checked ? 'checked' : ''" @click="checkRadio(option)"
      v-for="option in props.modelValue ?? []" :key="option.option">{{
        option.option
      }}</div>
  </div>
</template>

<script setup lang="ts">
import { defineProps } from 'vue';

type Props = {
  modelValue: Array<{ option: string, checked: boolean }> | undefined,
  /** 是否禁用 */
  disable?: boolean
}

// 参数
const props = withDefaults(defineProps<Props>(), {
  modelValue: undefined,
  disable: false
})

// 事件
const emits = defineEmits(['update:modelValue'])

/** 点击进行选项切换 */
const checkRadio = (option: { option: string, checked: boolean }) => {
  // 如果已禁用则直接返回
  if (props.disable) return
  const newModelValue = props.modelValue?.map(item => {
    if (item.option === option.option) {
      return {
        ...item,
        checked: !item.checked
      }
    }
    return {
      ...item,
      checked: false
    }
  })
  emits('update:modelValue', newModelValue)
}

</script>

<style scoped lang="scss">
.radio-group {
  width: 100%;
  display: grid;
  // 自动创建列，每列最小宽度100px，最大宽度1fr
  grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
  justify-items: center;

  .radio {
    font-size: 17px;
    line-height: 100%;
    position: relative;

    // 未选中
    &::before {
      position: absolute;
      left: -26px;
      top: 50%;
      transform: translateY(-50%);

      content: '';
      width: 18px;
      height: 18px;
      border-radius: 50%;
      border: 1px solid #ff5875;
    }

    // 选中
    &.checked::after {
      position: absolute;
      left: -23px;
      top: 50%;
      transform: translateY(-50%);

      content: '';
      display: block;
      width: 14px;
      height: 14px;
      border-radius: 50%;
      background-color: #ff5875;
    }
  }
}
</style>
